<template>
    <div class="addDetailsForm">
        <a-form
                :model="formState"
                name="addToDoDetails"
                v-bind="formItemLayout"
                ref="formRef"
                :rules="rules"
                @finish="onFinish"
                @finishFailed="onFinishFailed"
                style="margin-top: 20px"
        >
            <a-form-item
                    name="details"
                    label="待办事件"
            >
                <a-textarea v-model:value="formState.details"/>
            </a-form-item>
            <a-form-item
                    name="date"
                    label="截止时间"
            >
                <a-date-picker v-model:value="formState['date']" value-format="YYYY-MM-DD"/>
            </a-form-item>
            <a-form-item :wrapper-col="{ ...formItemLayout.wrapperCol, offset: 8 }">
                <a-button type="primary" @click.prevent="onSubmit">添加</a-button>
            </a-form-item>
        </a-form>
    </div>
    <div>
        <div style="height: 20px"></div>
        <a-table
                bordered
                :columns="columns"
                :data-source="dataList"
                @change="onChange"
        >
            <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                    <a-tag :color="record.status === 1 ? 'green' : 'red'">
                        {{ record.status === 0 ? '未完成' : '已完成' }}
                    </a-tag>
                </template>
                <template v-if="column.key === 'operation'">
                    <div class="operationColumn">
                        <a-button
                            type="primary"
                            ghost
                            :disabled="record.status!==0"
                            @click="() => {
                                record.status = 1;
                                finishedNumber++;
                                unfinishedNumber--;
                            }"
                        >
                            标记为完成
                        </a-button>
                        <div style="width: 10px"></div>
                        <a-button type="primary" ghost @click="deleteData(record.key)">
                            删除
                        </a-button>
                    </div>
                </template>
            </template>
            <template #summary>
                <a-table-summary fixedTop>
                    <a-table-summary-row>
                        <div class="listSummary">
                            <div style="font-weight: bold;font-size: 16px;margin-left: 20px">总计:{{dataList.length}}</div>
                            <div style="font-weight: bold;color: green;font-size: 16px;margin-left: 20px">已完成:{{finishedNumber}}</div>
                            <div style="font-weight: bold;color: red;font-size: 16px;margin-left: 20px">未完成:{{unfinishedNumber}}</div>
                        </div>
                    </a-table-summary-row>
                </a-table-summary>
            </template>
        </a-table>
    </div>
</template>

<script lang="ts" setup>
import {computed, reactive, ref, toRaw} from 'vue';
import type {Rule} from "ant-design-vue/es/form";
import type { TableColumnType, TableProps } from 'ant-design-vue';
import type {Ref} from 'vue';

const formRef = ref();

const formState = reactive({
    details: '',
    date: '',
})

interface DataType {
    key: number;
    status: number;
    date: string;
    details: string;
}

const dataList: Ref<DataType[]> = ref([]);
let dataListKey = 0;
const finishedNumber = ref(0);
const unfinishedNumber = ref(0);

const formItemLayout = {
    labelCol: {
        xs: {span: 24},
        sm: {span: 8},
    },
    wrapperCol: {
        xs: {span: 24},
        sm: {span: 8},
    },
};

const rules: Record<string, Rule[]> = {
    details: [{required: true, message: '请输入待办事项', trigger: 'change'}],
    date: [{required: true, message: '请输入截止日期', trigger: 'change'}]
};

/**
 * 添加数据
 */
const onSubmit = () => {
    formRef.value
        .validate()
        .then(() => {
            const data = {
                key: dataListKey++,
                status: 0,
                date: formState.date,
                details: formState.details,
            }
            dataList.value.push(data);
            console.log('values', formState, toRaw(formState));
            formRef.value.resetFields();
            console.log('dataListKey', dataListKey);
        })
        .catch(error => {
            console.log('error', error);
        });
};
const onFinish = (values: any) => {
    console.log('Success:', values, formState);
};

const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
};

const deleteData = (key: number) => {
    dataList.value = dataList.value.filter((item: DataType) => item.key !== key);
    finishedNumber.value = dataList.value.filter((item: DataType) => item.status === 1).length;
    unfinishedNumber.value = dataList.value.filter((item: DataType) => item.status === 0).length;
}

/**
 * 表头配置
 */
const columns = [
    {
        title: '状态',
        key: 'status',
        width: 100,
        dataIndex: 'status',
        filters: [
            {
                text: '未完成',
                value: 0,
            },
            {
                text: '已完成',
                value: 1,
            },
        ],
        onFilter: (value: number, record: DataType) => record.status === value,
        sorter:{
            compare: (a: DataType, b: DataType) => a.status - b.status,
            multiple: 2,
        },
    },
    {
        title: '截止时间',
        key: 'date',
        width: 100,
        dataIndex: 'date',
        sorter:{
            compare: (a: DataType, b: DataType) => new Date(a.date).getTime() - new Date(b.date).getTime(),
            multiple: 1,
        }
    },
    {
        title: '待办事件',
        key: 'details',
        width: 300,
        dataIndex: 'details',
    },
    {
        title: '操作',
        key: 'operation',
        width: 100,
        dataIndex: 'operation',
    },
];

/**
 * 表格排序
 */
const onChange: TableProps<DataType>['onChange'] = (pagination, filters, sorter) => {
    console.log('params', pagination, filters, sorter);
};

/**
 * 数字补零
 */
const padStart = (num: number) => {
    if(num<10) return `0${num}`;
    return num.toString();
}

/**
 * 初始化自动生成数据
 */
const today = new Date();
for (let i = 0; i < 35; i++) {
    // 随机生成status
    const status = Math.floor(Math.random() * 2); // 0 或 1
    if(status===1) finishedNumber.value++;
    else unfinishedNumber.value++;
    // 生成未来的日期
    const futureDate = new Date(today);
    futureDate.setDate(futureDate.getDate() + i); // 增加i天
    const formattedDate = `${futureDate.getFullYear()}-${padStart(futureDate.getMonth() + 1)}-${padStart(futureDate.getDate())}`;

    // 生成details
    const details = `待办事项${i + 1}`;
    dataList.value.push({
        key: dataListKey++,
        status,
        date: formattedDate,
        details: details,
    });
}


</script>

<style scoped>
.addDetailsForm {
    background-color: white;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.operationColumn {
    display: flex;
}
.listSummary{
    height: 30px;
    width: 100%;
    display: flex;
}

</style>
